package com.sky.controller.admin;

import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.IIOException;
import java.io.IOException;
import java.util.UUID;

/**
 *
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口,文件上传")
public class CommonController {
//    private final AliOssProperties aliOssProperties;
//
//    public CommonController(AliOssProperties aliOssProperties) {
//        this.aliOssProperties = aliOssProperties;
//    }
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestPart MultipartFile file){
        log.info("文件上传:{}",file);

        /**
         * 1.获取文件的原始文件名
         * 2.修改原始文件名 获取文件的后缀名
         * 3.UUID生产字符串当作文件名
         * 4.调用AliossUtils 上传文件
         * 5.返回上传文件的访问路径
         */
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String newFileName=UUID.randomUUID().toString()+suffix;
        //AliossUtil
//        AliOssUtil aliOssUtil = new AliOssUtil(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKeyId(), aliOssProperties.getAccessKeySecret(), aliOssProperties.getBucketName());
        try {
            String fileUrl=aliOssUtil.upload(file.getBytes(),newFileName);
            return Result.success(fileUrl);
        }catch (IIOException e){
            return Result.error("上传文件失败");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
